package com.hbnu.personaldiaryweb.controller;

import com.hbnu.personaldiaryweb.entity.Diary;
import com.hbnu.personaldiaryweb.service.DiaryService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

//日记请求控制器
@Controller
public class DiaryController {

    //需要日记服务对象
    @Autowired
    private DiaryService diaryService;

    //插入日记功能，请求地址是 /diary/insert
    //如果插入成功返回 {success: true}，如果插入失败返回 {success: false, message: "失败原因"}
    @RequestMapping("/diary/insert")
    @ResponseBody
    public Map<String, Object> insertDiary(@RequestBody Map<String, String> map, HttpServletRequest request) {
        // 创建返回结果
        Map<String, Object> result = new HashMap<>();

        // 获取当前用户 ID（从会话中获取）
        String userId = (String) request.getSession().getAttribute("usersId");
        if (userId == null) {
            result.put("success", false);
            result.put("message", "用户未登录，请先登录");
            return result;
        }

        // 获取参数
        String title = map.get("title");
        String diary_body = map.get("diary_body"); // 使用 diary_body 作为字段名
        String label = map.get("label");
        String date_time = map.get("date_time");
        String life_state = map.get("life_state");

        // 日志调试
        System.out.println("接收到的参数：" + map);
        System.out.println("用户 ID：" + userId);

        // 参数检查
        if (title == null || title.trim().isEmpty()) {
            result.put("success", false);
            result.put("message", "日记标题不能为空");
            return result;
        }
        if (diary_body == null || diary_body.trim().isEmpty()) {
            result.put("success", false);
            result.put("message", "日记内容不能为空");
            return result;
        }
        if (label == null || label.trim().isEmpty()) {
            result.put("success", false);
            result.put("message", "日记标签不能为空");
            return result;
        }

        // 创建日记对象
        Diary diary = new Diary();
        diary.setUser_id(userId);
        diary.setTitle(title);
        diary.setDiary_body(diary_body); // 使用 diary_body 作为字段名
        diary.setLabel(label);
        diary.setDate_time(date_time);
        diary.setLife_state(life_state != null ? life_state : "0"); // 设置默认值

        // 日志调试
        System.out.println("日记对象：" + diary);

        // 插入日记
        try {
            int insertResult = diaryService.insertDiary(diary);
            System.out.println("插入结果：" + insertResult);
            if (insertResult > 0) {
                result.put("success", true);
                result.put("message", "日记插入成功");
            } else {
                result.put("success", false);
                result.put("message", "日记插入失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "服务器错误");
        }

        // 日志调试
        System.out.println("返回结果：" + result);

        return result;
    }


    /**
     * 获取对应用户的所有唯一标签
     *
     * @param user_id 用户 ID
     * @return 标签列表
     */
    @GetMapping("/diary/labels")
    @ResponseBody
    public List<String> getLabelsByUser(HttpServletRequest request) {
        String user_id = request.getParameter("user_id");
        System.out.println("开始获取所有标签");
        System.out.println("user_id:" + user_id);
        return diaryService.getLabelsByUser(user_id);
    }

    @RequestMapping("/test")
    @ResponseBody //有响应的
    public String test(HttpServletRequest request) {
        return "hello";
    }

    /**
     * 获取对应用户和标签的日记简要数据
     *
     * @param user_id 用户 ID
     * @param label   标签
     * @return 日记简要数据列表
     */
    @RequestMapping("/diary/list")
    @ResponseBody
    public List<Diary> getDiariesMiniByUserAndLabel(@RequestParam String user_id, @RequestParam String label) {
        System.out.println("开始获取所有对应缩略");
        System.out.println(diaryService.getDiariesMiniByUserAndLabel(user_id, label));

        return this.diaryService.getDiariesMiniByUserAndLabel(user_id, label);
    }


    @RequestMapping("/getDiary")
    @ResponseBody
    public Diary getDiaryById(@RequestParam String id, HttpServletRequest request) {
        System.out.println("开始获取完整日记");
        System.out.println("id:" + id );
        String userId = (String) request.getSession().getAttribute("usersId");

        //按编号获取
        Diary diary = this.diaryService.getDiaryById(id);


        //判断是否是自己的日记
        if (!diary.getUser_id().equals(userId)) {
            System.out.println("不是这个用户的日记");
            return null;
        }

        return diary;
    }

    @RequestMapping("/deleteDiary")
    @ResponseBody
    public String deleteDiary(@RequestParam String id, HttpServletRequest request) {
        System.out.println("开始删除完整日记");
        System.out.println("id:" + id );
        String userId = (String) request.getSession().getAttribute("usersId");

        //按编号获取
        Diary diary = this.diaryService.getDiaryById(id);

        //判断是否是自己的日记
        if (!diary.getUser_id().equals(userId)) {
            System.out.println("不是这个用户的日记");
            return "不是这个用户的日记";
        }

        //删除
        this.diaryService.deleteDiaryById(id);

        return "ok";
    }

    @RequestMapping("/updateDiary")
    @ResponseBody
    public String updateDiary(@RequestBody Map<String,String>map, HttpServletRequest request) {
        System.out.println("开始删除完整日记");

        String userId = (String) request.getSession().getAttribute("usersId");
        String id=map.get("id");
        String diary_body=map.get("diary_body");
        System.out.println("id:" + id );
        System.out.println("diary_body:" + diary_body );
        //按编号获取
        Diary diary = this.diaryService.getDiaryById(id);

        //判断是否是自己的日记
        if (!diary.getUser_id().equals(userId)) {
            System.out.println("不是这个用户的日记");
            return "不是这个用户的日记";
        }

        //修改
        diary.setDiary_body(diary_body);
        this.diaryService.updateDiary(diary);


        return "ok";
    }


    //向
//    @RequestMapping("/diary/view")
//    @ResponseBody
//    public Map<String, Object> viewDiary(@RequestBody Map<String, String> map, HttpServletRequest request) {
//        // 创建返回结果
//        Map<String, Object> result = new HashMap<>();
//
//        // 获取当前用户 ID（从会话中获取）
//        String userId = (String) request.getSession().getAttribute("usersId");
//        if (userId == null) {
//            result.put("success", false);
//            result.put("message", "用户未登录，请先登录");
//            return result;
//        }
//
//
//
//
//
//    }


}